<template>
  <div>
    <h1>User Management</h1>
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>User List</span>
          <el-button type="primary" @click="showAddDialog = true" v-if="canAddUser">Add User</el-button>
        </div>
      </template>
      <div class="card-content">
        <el-table :data="users" style="width: 100%">
          <el-table-column prop="username" label="Username" width="180" />
          <el-table-column prop="email" label="Email" width="220" />
          <el-table-column prop="roles" label="Roles" />
          <el-table-column label="Status" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status ? 'success' : 'danger'">
                {{ scope.row.status ? 'Active' : 'Disabled' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="Operations" width="180">
            <template #default="scope">
              <el-button size="small" @click="handleEdit(scope.row)" v-if="canEditUser">Edit</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)" v-if="canDeleteUser">Delete</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- Add User Dialog -->
    <el-dialog v-model="showAddDialog" title="Add New User" width="30%">
      <el-form :model="newUser" :rules="rules" ref="addFormRef" label-width="100px">
        <el-form-item label="Username" prop="username" required>
          <el-input v-model="newUser.username" />
        </el-form-item>
        <el-form-item label="Email" prop="email" required>
          <el-input v-model="newUser.email" />
        </el-form-item>
        <el-form-item label="Password" prop="password" required>
          <el-input v-model="newUser.password" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">Cancel</el-button>
        <el-button type="primary" @click="handleAdd" :disabled="addFormRef?.validateField('username') || addFormRef?.validateField('email') || addFormRef?.validateField('password')">Confirm</el-button>
      </template>
    </el-dialog>

    <!-- Edit User Dialog -->
    <el-dialog v-model="showEditDialog" title="Edit User" width="30%">
      <el-form :model="editingUser" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="Username">
          <el-input v-model="editingUser.username" disabled />
        </el-form-item>
        <el-form-item label="Email" prop="email" required>
          <el-input v-model="editingUser.email" />
        </el-form-item>
        <el-form-item label="Status">
          <el-switch v-model="editingUser.status" active-text="Active" inactive-text="Disabled" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">Cancel</el-button>
        <el-button type="primary" @click="handleUpdate" :disabled="editFormRef?.validateField('email')">Save</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api'
import { useAuthStore } from '@/store/auth'

const authStore = useAuthStore()

const users = ref([])
const showAddDialog = ref(false)
const showEditDialog = ref(false)

const newUser = ref({
  username: '',
  email: '',
  password: ''
})

const editingUser = ref({
  id: null,
  username: '',
  email: '',
  status: true
})

const rules = {
  username: [
    { required: true, message: 'Please input username', trigger: 'blur' }
  ],
  email: [
    { required: true, message: 'Please input email', trigger: 'blur' },
    { type: 'email', message: 'Please input a valid email address', trigger: 'blur' }
  ],
  password: [
    { required: true, message: 'Please input password', trigger: 'blur' }
  ]
}

const editRules = {
  email: [
    { required: true, message: 'Please input email', trigger: 'blur' },
    { type: 'email', message: 'Please input a valid email address', trigger: 'blur' }
  ]
}

const addFormRef = ref(null)
const editFormRef = ref(null)

const fetchUsers = async () => {
  try {
    const response = await api.user.getUsers()
    users.value = response.data.map(user => ({
      id: user.id,
      username: user.username,
      email: user.email,
      status: user.enabled,
      roles: user.roles?.map(r => r.name).join(', ') || ''
    }))
  } catch (error) {
    ElMessage.error('Failed to fetch users')
    console.error(error)
  }
}

const handleEdit = (user) => {
  editingUser.value = {
    id: user.id,
    username: user.username,
    email: user.email,
    status: user.enabled
  }
  showEditDialog.value = true
}

const handleUpdate = async () => {
  try {
    await editFormRef.value.validate()
    await api.user.updateUser(editingUser.value.id, {
      email: editingUser.value.email,
      enabled: editingUser.value.status
    })
    await fetchUsers()
    showEditDialog.value = false
    ElMessage.success('User updated successfully')
  } catch (error) {
    ElMessage.error(error.response?.data?.message || 'Failed to update user')
  }
}

const handleDelete = async (user) => {
  try {
    await ElMessageBox.confirm(
      `Delete user ${user.username}? This action cannot be undone.`,
      'Warning',
      { 
        type: 'warning',
        customClass: 'delete-confirm',
        center: true
      }
    )
    await api.user.deleteUser(user.id)
    await fetchUsers()
    ElMessage.success('User deleted successfully')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('Failed to delete user')
    }
  }
}

const handleAdd = async () => {
  try {
    await addFormRef.value.validate()
    await api.user.createUser(newUser.value)
    await fetchUsers()
    showAddDialog.value = false
    newUser.value = { username: '', email: '', password: '' }
    ElMessage.success('User created successfully')
  } catch (error) {
    ElMessage.error(error.response?.data?.message || 'Failed to create user')
  }
}

const canAddUser = computed(() => authStore.user?.roles?.includes('ROLE_ADMIN'))
const canEditUser = computed(() => authStore.user?.roles?.includes('ROLE_ADMIN'))
const canDeleteUser = computed(() => authStore.user?.roles?.includes('ROLE_ADMIN'))

onMounted(async () => {
  await fetchUsers()
})
</script>

<style scoped>
.box-card {
  margin: 20px auto;
  max-width: 1200px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 18px;
  padding: 15px 20px;
}
.card-content {
  padding: 20px;
}

@media (max-width: 768px) {
  .box-card {
    margin: 10px;
  }
  .card-header {
    flex-direction: column;
    gap: 10px;
  }
}
</style>
